(function(window)
{
  "use strict";

  var dice;

  var fst_render;
  var snd_render;

  function Bizkit4Hangout()
  {
    gapi.hangout.onApiReady.add(this.onApiReady.bind(this));
    fst_render = new DiceRenderer(document.getElementById("first_dice_canvas").getContext("2d"), 50, 50);
    snd_render = new DiceRenderer(document.getElementById("second_dice_canvas").getContext("2d"), 50, 50);
  }

  Bizkit4Hangout.prototype.onApiReady = function(event)
  {
    if (event.isApiReady === true)
    {
      gapi.hangout.data.clearValue("dice");
      gapi.hangout.data.onStateChanged.add(this.newState.bind(this));
    }
  };


  Bizkit4Hangout.prototype.onParticipantsChanged = function(event)
  {
  };


  Bizkit4Hangout.prototype.newState = function()
  {
    var raw_res = gapi.hangout.data.getValue("dice");
    if (undefined !== raw_res)
    {
      dice = JSON.parse(gapi.hangout.data.getValue("dice"));
      dice = new BizkitContext(dice.d1, dice.d2);
      fst_render.render(dice.d1);
      snd_render.render(dice.d2);
      $("#res_msg").empty();
      if (dice.isBizkit())
        $("#res_msg").text("");
      else if (dice.isDouble())
        $("#res_msg").text("distribue " + dice.d1);
      else if (dice.isPerave())
        $("#res_msg").text("tu bois parce que t'es pérave");
      else if (dice.isNewRule())
        $("#res_msg").text("nouvelle règle");
      else if (dice.isPrevDrinks())
        $("#res_msg").text("celui d'avant boit");
      else if (dice.isDrinks())
        $("#res_msg").text("tu bois");
      else if (dice.isNextDrinks())
        $("#res_msg").text("celui d'après boit");
      else
        $("#res_msg").text("rien");
    }
  };


  var rndm_nb = function()
  {
    return Math.floor(Math.random() * 6) + 1;
  };

  $("#play_btn").click(function()
  {
    dice = new BizkitContext (rndm_nb(), rndm_nb());
    gapi.hangout.data.setValue("dice", JSON.stringify(dice));
  });

  var hangout = new Bizkit4Hangout();

}(window));
